package com.rjkj.medicalwaste.ui.home

import android.bluetooth.BluetoothDevice
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.inuker.bluetooth.library.utils.BluetoothUtils
import com.rjkj.medicalwaste.MainActivity
import com.rjkj.medicalwaste.R
import com.rjkj.medicalwaste.base.BaseFragment
import com.rjkj.medicalwaste.bean.BlueConnectResult
import com.rjkj.medicalwaste.bean.GarbageBean
import com.rjkj.medicalwaste.databinding.FragmentHomeBinding
import com.rjkj.medicalwaste.livedatabus.LiveDataBus
import com.rjkj.medicalwaste.utils.AppPrefsUtils
import com.rjkj.medicalwaste.utils.BaseConstant
import com.rjkj.medicalwaste.viewmodels.BluetoothControlViewModel
import com.rjkj.medicalwaste.viewmodels.CollectMainViewModel
import com.rjkj.medicalwaste.viewmodels.HomeViewModel
import com.rjkj.medicalwaste.viewmodels.UserViewModel
import com.rjkj.medicalwaste.viewmodels.provider.MainViewModelProvider
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class HomeFragment : BaseFragment<FragmentHomeBinding>(), View.OnClickListener {
    private val userViewModel: UserViewModel by activityViewModels {
        MainViewModelProvider.provideUserModel(requireContext())
    }
    private val bluetoothControlViewModel: BluetoothControlViewModel by activityViewModels()
    private val collectMainViewModel: CollectMainViewModel by activityViewModels {
        MainViewModelProvider.providerCollectMainModel(requireContext())
    }
    private val viewModel: HomeViewModel by viewModels()
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val binding = FragmentHomeBinding.inflate(inflater, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.userData = userViewModel
        binding.homeData = viewModel
        onSubscribeUi(binding)
        return binding.root
    }

    override fun onResume() {
        super.onResume()
        viewModel.homeData(
            userViewModel.getUrl(),
            userViewModel.getSerial(),
            userViewModel.hospitalId.value!!
        )
        collectMainViewModel.cleanList()
    }

    override fun onSubscribeUi(binding: FragmentHomeBinding) {
        binding.btCollect.setOnClickListener(this)
        binding.btOutbound.setOnClickListener(this)
        binding.btStorage.setOnClickListener(this)
        binding.btExit.setOnClickListener(this)
        binding.btWaitPack.setOnClickListener(this)
        initTip(viewModel)
        initDialog(userViewModel)
        lifecycleScope.launchWhenResumed {
            val mac = AppPrefsUtils.getString(BaseConstant.BLUETOOTH_MAC)
            val mDevice: BluetoothDevice? = BluetoothUtils.getRemoteDevice(mac)
            if(mDevice!=null){
                bluetoothControlViewModel.bluetoothTry.value = BlueConnectResult(mac, mDevice.type)
            }
        }
        LiveDataBus.get().with(MainActivity.SCAN_DATA, String::class.java).observe(
            viewLifecycleOwner, {
                if (it == "forXlbTest") {
                    findNavController().navigate(R.id.action_homeFragment_to_xlbTestFragment)
                }
            })
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.bt_collect -> findNavController().navigate(R.id.action_homeFragment_to_collectScanFragment)
            R.id.bt_outbound -> findNavController().navigate(R.id.action_homeFragment_to_outboundScanFragment)
            R.id.bt_storage -> findNavController().navigate(R.id.action_homeFragment_to_storageScanFragment)
            R.id.bt_exit -> requireActivity().onBackPressed()
            R.id.bt_wait_pack -> {
                viewModel.homeData(
                    userViewModel.getUrl(),
                    userViewModel.getSerial(),
                    userViewModel.hospitalId.value!!
                )
                findNavController().navigate(R.id.action_homeFragment_to_waitPackDetailDialog)
            }
        }
    }

    override fun showAreYouSureDialog() {
        lifecycleScope.launchWhenResumed {
            userViewModel.uploadEvent.value = true
            val hospitalId = userViewModel.hospitalId.value ?: ""
            val collectState = userViewModel.userRepository.findUpdateState(
                hospitalId,
                GarbageBean.collectState,
            )
            if (collectState.isNotEmpty()) {
                userViewModel.uploadGarbage(
                    garbageBeanList = collectState,
                    successState = GarbageBean.collectState,
                    failState = GarbageBean.nullState
                )
            }

            val storeState = userViewModel.userRepository.findUpdateState(
                hospitalId,
                GarbageBean.storeState,
            )
            if (storeState.isNotEmpty()) {
                userViewModel.uploadGarbage(
                    garbageBeanList = storeState,
                    successState = GarbageBean.storeState,
                    failState = GarbageBean.nullState
                )
            }

            val boxState = userViewModel.userRepository.findUpdateState(
                hospitalId,
                GarbageBean.boxState,
            )
            if (boxState.isNotEmpty()) {
                userViewModel.uploadGarbage(
                    garbageBeanList = boxState,
                    successState = GarbageBean.boxState,
                    failState = GarbageBean.nullState
                )
            }
            val outboundState = userViewModel.userRepository.findUpdateState(
                hospitalId,
                GarbageBean.outboundState
            )
            if (outboundState.isNotEmpty()) {
                userViewModel.uploadGarbage(
                    garbageBeanList = outboundState,
                    successState = GarbageBean.outboundState,
                    failState = GarbageBean.nullState
                )
            }

            delay(500)
            userViewModel.uploadEvent.value = false
            findNavController().navigateUp()
        }
    }

}